package com.spring_mysql_redis.annotation.currentUser;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.spring_mysql_redis.annotation.CurrentUser;
import com.spring_mysql_redis.entity.Users;
import com.spring_mysql_redis.mapper.UsersMapper;
import com.spring_mysql_redis.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CurrentUser.class) &&
                parameter.getParameterType().isAssignableFrom(Users.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) {
        // header中获取用户token,存到前端
        String token = request.getHeader("token");

        Integer id;
        if(token != null){
            try {
                //解密token，取出第0个参数（即-存入的id）
                id = Integer.parseInt(JWT.decode(token).getAudience().get(0));
                System.out.println("id的值" + id);
            } catch (JWTDecodeException j) {
                //若取出过程出错，则报一个错误
                throw new RuntimeException("401");
            }
            // TODO 根据userId获取User信息，直接创建一个User对象。
            Users user = usersMapper.selectById(id);
            return user;
        }
        return null;
    }
}
